#include <iostream>
#include <string>
#include <cstdlib>
#include <map>

#include "hunterAPI.hpp"
#include "hunterHTTP.hpp"

using namespace std;

int main()
{
	HunterAPI::HiveMind hm("./database");
	freopen("./log", "w+", stderr);

	string cookie = getCookie();
	HunterAPI::Player tar;
	string s = getQuery();
	int tarid = strtoint(s); 
	if (hm.getPlayerById(tarid, tar))
	{
		cout << "Content-type: text/html;\n\n";
		o_header("Fail");
		o_internal_error("getPlayer error");
		o_footer();
		return 0;
	}
	
	int id = -1;
	if (hm.verifyCookie(cookie, id) || id == -1)
	// login failed
	{
		cout << "Content-type: text/html;\n\n";
		o_header("Fail");
		o_login_error("Session expired w/ " + cookie);
		o_footer();
		return 0;
	}
	
	HunterAPI::Player pl;
	hm.getPlayerById(id, pl);

	// Player info goes here	
	cout << "Content-type: text/html;\n\n";	
	o_header("Club -- View Player " + inttostr(tar.id));
	o_upper_visible(pl);
	
	int rep;
	if (hm.getPlayerRep(tar, rep))
	{
		cout << "Content-type: text/html;\n\n";
		o_header("Fail");
		o_internal_error("getPlayerRep error");
		o_footer();
		return 0;
	}

	cout << "<script>function limg(r){if (r > 0){document.getElementById(\"arwup\").style.height = \'20px\';document.getElementById(\"arwup\").style.width = \'20px\';document.getElementById(\"arwdown\").style.height = \'16px\';document.getElementById(\"arwdown\").style.width = \'16px\';}else if (r < 0) {document.getElementById(\"arwdown\").style.height = \'20px\';document.getElementById(\"arwdown\").style.width = \'20px\';document.getElementById(\"arwup\").style.height = \'16px\';document.getElementById(\"arwup\").style.width = \'16px\';}}function showForm(r){limg(r);dv = document.getElementById(\"div0\");dv.style.visibility = \"visible\";dv.style.height = \"\";dv.innerHTML = \"<form method = \'post\' action = \'" << path_home << "/cgi-bin/say.cgi?query=\" + r + \"&from=" << tar.id << "\'><b>Please</b>, leave a comment:<br><input name = \'text\' type = \'text\'><br><input type = \'submit\'></form>\";}</script>";

	cout << "<center><table><tr><td>";
	
	cout << "<table><tr><td width = 200>?</td><td width = 200>...</td></tr>";
	cout << "<tr><td>ID</td><td>" << tar.id << "</td></tr>";
	cout << "<tr><td>Name</td><td>" << tar.username << "</td></tr>";
	cout << "<tr><td>Rating</td><td>" << tar.rating << "</td></tr>";
	cout << "<tr><td>Reputation</td><td>&nbsp;<img id = \"arwup\" onClick = \"javascript:showForm(1)\" style = \"width:16px;height:16px;\" src = \"" << path_home << "/cgi-bin/img/24.png\"> &nbsp; " << rep << " &nbsp; <img id = \"arwdown\" onClick = \"javascript:showForm(-1)\" style = \"height:16px;width:16px;\"src = \"" << path_home << "/cgi-bin/img/07.png\"></td></tr>";
	cout << "<tr> <td colspan = 2> <div id = 'div0' style = \"visibility:hidden;height:0px;\"></div></td></tr>";
	cout << "</table>";
	
	cout << "</td><td>";
	
	// commendations goes here
	
	cout << "</td></tr></table></center>";
	
	o_footer();
	
	return 0;
}
